<template>
  <!--新增/编辑任务-->
  <vx-popup :title="dialogTitle" width="970px" @close="cancelSubmit" :active.sync="dialogVisible" @confirmPopup="handleSubmit" @cancelPopup="cancelSubmit">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" class="demo-ruleForm">
      <div class="insp-task-addPage-basic">
        <el-row justify="space-between" :gutter="20">
          <el-col :span="12">
            <el-form-item label="任务名称 :" prop="name" label-width="95px" clearable>
              <el-input v-model="ruleForm.name" placeholder="请输入任务名称" size="small" style="width: 100%" clearable :disabled="editFlage"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="巡检类型 :" prop="inspType" label-width="95px">
              <el-select v-model="ruleForm.inspType" placeholder="请选择巡检类型" size="small" style="width: 100%" :disabled="editFlage" clearable>
                <el-option label="日常巡检" :value="0"></el-option>
                <el-option label="定期巡检" :value="1"></el-option>
                <!-- <el-option label="特殊巡检" :value="2"></el-option> -->
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <div class="insp-task-addPage-line" v-for="(item, index) in ruleForm.inspBridges" :key="index" style="height: 118px">
        <div class="insp-task-addPage-left">
          <div class="insp-task-addPage-item">
            <el-form-item label="巡检桥梁 :" :prop="'inspBridges[' + index + '].bridge'" :rules="{ required: true, message: '请选择巡检桥梁', trigger: 'change' }" label-width="95px">
              <el-select
                filterable
                v-model="item.bridge"
                :disabled="editFlage"
                placeholder="请选择巡检桥梁"
                size="small"
                style="width: 165px"
                @change="(event) => handleBridgeChange(event, index)"
                value-key="id"
                clearable
              >
                <el-option v-for="temp in bridgeOptions" :key="temp.id" :label="temp.name" :value="temp"> </el-option>
              </el-select>
            </el-form-item>
          </div>
          <div class="insp-task-addPage-item">
            <!-- <el-form-item label="巡检项 :" :prop="'inspBridges[' + index + '].name'" :rules="{ required: false, message: '请选择巡检项', trigger: 'change' }" label-width="95px">
              <el-cascader
                v-model="item.name"
                :options="deasePosOptions[index] || []"
                @change="(event) => handleChangeDeasePos(event, index)"
                :key="isResouceShow"
                :props="{ label: 'name', value: 'value', children: 'children' }"
                size="small"
                style="width: 165px"
                placeholder="请选择巡检项"
                clearable
              >
              </el-cascader>
            </el-form-item> -->
          </div>
          <div class="insp-task-addPage-item">
            <el-form-item label="巡检员 :" :prop="'inspBridges[' + index + '].itemUserList'" :rules="{ required: true, message: '请选择巡检员', trigger: 'change' }" label-width="95px">
              <el-select v-model="item.itemUserList" filterable :disabled="editFlage" placeholder="请选择巡检员" size="small" multiple collapse-tags style="width: 165px" clearable>
                <el-option v-for="item in personOptions" :key="item.realId" :label="item.name" :value="`${item.realId};${item.name}`"> </el-option>
                <div style="text-align: center">
                  <el-pagination
                    @current-change="handlePageChange_sel"
                    :current-page.sync="currentPage_sel"
                    :hide-on-single-page="true"
                    :page-size="pagesize_sel"
                    layout="prev, pager, next"
                    :total="recordsTotal_sel"
                  >
                  </el-pagination>
                </div>
              </el-select>
            </el-form-item>
          </div>

          <div class="insp-task-addPage-item">
            <el-form-item label="巡检规范 :" :prop="'inspBridges[' + index + '].inspStandard'" :rules="{ required: true, message: '请选择巡检规范', trigger: 'change' }" label-width="95px">
              <el-select v-model="item.inspStandard" placeholder="请选择巡检规范" size="small" style="width: 165px" clearable :disabled="editFlage">
                <el-option label="城市桥梁" :value="0"></el-option>
                <el-option label="道路桥梁" :value="1"></el-option>
              </el-select>
            </el-form-item>
          </div>

          <div class="insp-task-addPage-item">
            <el-form-item label="任务时间:" :prop="'inspBridges[' + index + '].sdt'" :rules="{ required: true, message: '请选择任务时间', trigger: 'change' }" label-width="95px">
              <el-date-picker
                v-model="item.sdt"
                type="date"
                size="small"
                placeholder="请选择开始时间"
                value-format="yyyy-MM-dd HH:mm:ss"
                format="yyyy-MM-dd"
                style="width: 165px"
                clearable
                :disabled="editFlage"
              >
              </el-date-picker>
            </el-form-item>
          </div>

          <div v-if="dialogdis" class="insp-task-addPage-item">
            <el-form-item label="任务周期 :" :prop="'inspBridges[' + index + '].duration'" :rules="{ required: true, message: '请输入任务周期', trigger: 'blur' }" label-width="95px">
              <el-input size="small" v-model="item.duration" placeholder="请输入" style="width: 165px" clearable type="number">
                <template slot="append">天</template>
              </el-input>
            </el-form-item>
          </div>
        </div>
        <!--        注释掉可以删除和新增按钮-->
        <!--        <div class="insp-task-addPage-right">-->
        <!--          <div class="insp-task-addPage-item">-->
        <!--            <el-form-item lable-width="0">-->
        <!--              <el-button circle size="mini" type="danger" style="margin-left: 10px" icon="el-icon-minus" @click="handleDeleteItem(item, index)"> </el-button>-->
        <!--            </el-form-item>-->
        <!--          </div>-->
        <!--        </div>-->
      </div>

      <!--      <div class="insp-task-addPage-btn">-->
      <!--        <el-button size="mini" type="primary" class="insp-task-addBtn" icon="el-icon-plus" @click="handleAddLine"> </el-button>-->
      <!--      </div>-->
    </el-form>
  </vx-popup>
</template>

<script>
export default {
  props: {
    createType: {
      type: Number,
      required: true,
      default: 4,
    },
  },
  data() {
    return {
      isResouceShow: 0,
      dialogTitle: '新增任务',
      dialogVisible: false,
      editId: '',
      bridgeOptions: [],
      dialogdis: true,
      personOptions: [],
      deasePosOptions: {},
      ruleForm: {
        name: '',
        inspType: '',
        inspBridges: [
          {
            bridge: '',
            name: [],
            inspStandard: '',
            sdt: '',
            duration: '',
            itemUserList: [],
          },
        ],
      },
      rules: {
        name: [
          {
            required: true,
            message: '请输入任务名称',
            trigger: 'blur',
          },
        ],
        inspType: [
          {
            required: true,
            message: '请选择巡检类型',
            trigger: 'change',
          },
        ],
      },
      currentPage_sel: 1,
      pagesize_sel: 10,
      recordsTotal_sel: 0,
      editFlage: false,
    }
  },
  created() {
    this.queryBridgeList()
    this.queryPersonList(1)
  },
  methods: {
    add(val) {
      this.editFlage = false
      this.emptyForm()
      this.editId = null
      if (this.createType === 1) {
        this.queryTmplById(val)
      }
      if (this.createType === 3) {
        this.queryPlanById(val)
      }
      this.dialogTitle = '新增任务'
      this.dialogVisible = true
      this.dialogdis = true
    },
    edit(val) {
      this.$refs['ruleForm'].resetFields()
      this.dialogTitle = '任务详情'
      this.dialogVisible = true
      this.editFlage = val ? true : false

      this.dialogdis = false
      this.queryTaskById(val)
    },
    emptyForm() {
      this.$refs['ruleForm'].resetFields()
      const emptyObj = {
        name: '',
        inspType: '',

        inspBridges: [
          {
            bridge: '',
            name: [],
            inspStandard: '',
            itemUserList: [],
            duration: '',
            sdt: '',
          },
        ],
      }
      this.ruleForm = emptyObj
    },
    queryBridgeList() {
      this.$api.bridge.AllTheBridges().then((response) => {
        if (response.data.success) {
          this.bridgeOptions = response.data.data[0]
        }
      })
    },
    queryTaskById(val) {
      this.$api.insp.queryTaskById(val).then((response) => {
        const _data = response.data.data
        this.ruleForm.name = _data.name
        // console.log(_data[0].ownName, '_data[0].itemList[0].ownName')
        // this.ruleForm.inspBridges[0].bridge = _data[0].ownName
        // this.ruleForm.inspBridges[0].bridge =
        this.ruleForm.inspType = _data.inspType
        this.ruleForm.inspBridges[0].bridge = _data.itemList[0].ownName
        let _inspBridges = _data.itemList.map((item, index) => {
          this.ruleForm.inspBridges[0].inspStandard = item.inspStandard
          this.ruleForm.inspBridges[0].sdt = item.sdt
          let _itemUserList = item.itemUserList.map((userItem) => `${userItem.userId};${userItem.userName}`) //编辑时放出来
          //  = item.itemUserList.map((userItem) => `${userItem.userName}`)
          this.ruleForm.inspBridges[0].itemUserList = _itemUserList
          let _ext1 = JSON.parse(item.ext1)
          this.handleBridgeChange(_ext1, index)
          // console.log(item, 'itemList')

          return {
            name: [`${item.constructionId};${item.constructionName}`, `${item.partsId};${item.partsName}`],
            inspStandard: item.inspStandard,
            bridge: _ext1,
            itemUserList: _itemUserList,
            sdt: item.sdt,
            duration: item.duration,
          }
        })

        let _ruleForm = {
          name: _data.name,
          inspType: _data.inspType,
          inspBridges: _inspBridges,
        }
        this.ruleForm = _ruleForm
      })
    },
    queryTmplById(val) {
      this.$api.insp.queryTmplById(val).then((response) => {
        const _data = response.data.data

        let _inspBridges = _data.itemList.map((item, index) => {
          let _itemUserList = item.itemUserList.map((userItem) => `${userItem.userId};${userItem.userName}`)
          let _ext1 = JSON.parse(item.ext1)
          this.handleBridgeChange(_ext1, index)
          return {
            name: [`${item.constructionId};${item.constructionName}`, `${item.partsId};${item.partsName}`],
            inspStandard: item.inspStandard,
            bridge: _ext1,
            itemUserList: _itemUserList,
          }
        })
        let _ruleForm = {
          name: _data.name,
          inspType: _data.inspType,
          inspBridges: _inspBridges,
        }
        this.ruleForm = _ruleForm
        this.$refs['ruleForm'].resetFields()
      })
    },
    queryPlanById(val) {
      this.$api.insp.queryPlanById(val).then((response) => {
        const _data = response.data.data

        let _inspBridges = _data.itemList.map((item, index) => {
          let _itemUserList = item.itemUserList.map((userItem) => `${userItem.userId};${userItem.userName}`)
          let _ext1 = JSON.parse(item.ext1)
          this.handleBridgeChange(_ext1, index)

          return {
            name: [`${item.constructionId};${item.constructionName}`, `${item.partsId};${item.partsName}`],
            inspStandard: item.inspStandard,
            bridge: _ext1,
            itemUserList: _itemUserList,
          }
        })
        let _ruleForm = {
          name: _data.name,
          inspType: _data.inspType,
          inspBridges: _inspBridges,
        }
        this.ruleForm = _ruleForm
        this.$refs['ruleForm'].resetFields()
      })
    },
    handleAddLine() {
      this.ruleForm.inspBridges.push({
        bridge: '',
        name: [],
        inspStandard: '',
        sdt: '',
        duration: '',
        itemUserList: [],
      })
    },
    handleDeleteItem(item, index) {
      this.ruleForm.inspBridges.splice(index, 1)
    },
    handleSubmit() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (!valid) {
          return false
        }
        let _userInfo = JSON.parse(localStorage.getItem('userInfo'))

        let _itemList = this.ruleForm.inspBridges.map((item) => {
          let _itemUserList = item.itemUserList.map((temp) => ({
            userId: temp.split(';')[0],
            userName: temp.split(';')[1],
          }))
          let _ext1 = {
            // ...item.bridge,
            id: item.bridge['id'] || '',
            name: item.bridge['name'] || '',
            lng: item.bridge['lng'] || '',
            lat: item.bridge['lat'] || '',
            bridgeTypeId: item.bridge['bridgeTypeId'] || '',
            bridgeTypeName: item.bridge['bridgeTypeName'] || '',
            province: item.bridge['provinceName'] ? item.bridge['provinceName'] : item.bridge['province'] ? item.bridge['province'] : '',
            city: item.bridge['municipalityName'] ? item.bridge['municipalityName'] : item.bridge['city'] ? item.bridge['city'] : '',
            area: item.bridge['regionName'] ? item.bridge['regionName'] : item.bridge['area'] ? item.bridge['area'] : '',
            standardName: item.bridge['standardName'] || '',
          }
          return {
            name: item.name.length > 0 ? `${item.name[0].split(';')[1]}/${item.name[1].split(';')[1]}` : '',
            constructionId: item.name.length > 0 ? item.name[0].split(';')[0] : '',
            constructionName: item.name.length > 0 ? item.name[0].split(';')[1] : '',
            partsId: item.name.length > 0 ? item.name[1].split(';')[0] : '',
            partsName: item.name.length > 0 ? item.name[1].split(';')[1] : '',
            ownId: item.bridge['id'] || '',
            ownName: item.bridge['name'] || '',
            inspTaskCfgPos: {
              ownId: item.bridge['id'] || '',
              ownName: item.bridge['name'] || '',
              lon: item.bridge['lng'] || '',
              lat: item.bridge['lat'] || '',
            },
            inspStandard: item.inspStandard,
            itemUserList: _itemUserList,
            sdt: item.sdt,
            duration: item.duration,
            ext1: JSON.stringify(_ext1),
          }
        })
        let _params = {
          createUserId: _userInfo['userid'] || '',
          createUserNmae: _userInfo['realname'] || '',
          createType: this.createType,
          name: this.ruleForm.name,
          sdt: this.ruleForm.inspBridges[0].sdt,
          inspType: this.ruleForm.inspType,
          itemList: _itemList,
        }

        if (this.editId) {
          _params.id = this.editId
        }
        if (this.editId) {
          this.dialogVisible = false
          this.$emit('closeAddInspTask')
          // this.$api.insp.updateTask(_params).then((response) => {
          //   if (response.data.success) {
          //     this.$vs.notify({
          //       text: '修改成功',
          //       color: 'success',
          //       icon: 'success',
          //     })

          //   }
          // })
        } else {
          this.$api.insp.addTask(_params).then((response) => {
            if (response.data.success) {
              this.$vs.notify({
                text: '新增成功',
                color: 'success',
                icon: 'success',
              })
              this.dialogVisible = false
              this.$emit('closeAddInspTask')
            }
          })
        }
      })
    },
    cancelSubmit() {
      this.dialogVisible = false
    },
    handleBridgeChange(event, index) {
      const _params = {
        bridgeTypeId: event['bridgeTypeId'] || '',
        pId: '-1',
        bridgeId: event['id'] || '',
      }
      this.queryConstructionModelTreeById(_params, index)
    },
    handleChangeDeasePos(event, index) {},
    deepDeasePosOptions(data) {
      let _arr = []
      let _obj = {}
      data.forEach((item) => {
        const _tmp = {
          ...item,
        }
        if (_tmp.children && _tmp.children.length > 0) {
          _tmp.children = this.deepDeasePosOptions(_tmp.children)
        }
        _obj = {
          id: _tmp.id,
          name: _tmp.name,
          value: `${_tmp.id};${_tmp.name}`,
        }
        if (_tmp.children && _tmp.children.length > 0) {
          _obj.children = _tmp.children
        }
        _arr.push(_obj)
      })
      return _arr
    },
    queryConstructionModelTreeById(_params, index) {
      this.$api.bridge.queryConstructionModelTreeById(_params).then((response) => {
        if (response.data.success) {
          ++this.isResouceShow
          this.deasePosOptions[index] = this.deepDeasePosOptions(response.data.data.children)
        }
      })
    },
    queryPersonList(pageIndex) {
      if (pageIndex && pageIndex === 1) {
        this.currentPage_sel = 1
      }
      const _params = {
        pageSize: this.pagesize_sel,
        pageNum: this.currentPage_sel,
        type: '0',
      }
      this.$api.personManager.getPersonList(_params).then((response) => {
        if (response.data.success) {
          this.personOptions = response.data.data
          this.recordsTotal_sel = response.data.recordsTotal
        }
      })
    },
    handlePageChange_sel(currentPage) {
      this.currentPage_sel = currentPage
      this.queryPersonList()
    },
  },
}
</script>
<style lang="scss" scoped>
@import '@/assets/scss/baseColor.scss';
@import '../insp.scss';
</style>
